#!python3
# -*- coding:utf-8 -*-

import sys
import array
import os
from matplotlib import pyplot

WAV_HEADER_SIZE = 44
fileName = 'qianqian8000_2channel.wav' # this file has 2 channels, 16 bit per sample
if len(sys.argv) == 2:
    fileName = sys.argv[1]
file = open(fileName, 'rb')
if fileName.lower().endswith('.wav'):
    file.seek(WAV_HEADER_SIZE)
base = 1 / (1<<15)

shortArray = array.array('h') # int16
size = (os.path.getsize(fileName)-file.tell()) // shortArray.itemsize
maxSample = 1000000 # if samples are too large, pyplot may overflow
interval = 2
if size > maxSample:
    interval = size // maxSample * 2
shortArray.fromfile(file, size) # faster than struct.unpack
file.close()
leftChannel = shortArray[::interval]
rightChannel = shortArray[1::interval]
del shortArray

def showPCM(leftChannel, rightChannel):
    llen = len(leftChannel)
    rlen = len(rightChannel)
    fig = pyplot.figure(1)

    pyplot.subplot(211)
    pyplot.title('pcm left channel')
    pyplot.plot(range(llen), leftChannel)

    pyplot.subplot(212)
    pyplot.title('pcm right channel')
    pyplot.plot(range(rlen), rightChannel)

    pyplot.show()
    # fig.savefig('pcm.pdf') # save figure to pdf file

showPCM(leftChannel, rightChannel)